package com.jahe.learn.netty4.customcodec;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @author: jahe.lai
 * @create: 2020-01-09 11:53
 */
public class LongCodecServer {

    private static Logger logger = LoggerFactory.getLogger(LongCodecServer.class);

    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 启动 和 配置属性相关的 辅助类
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 配置相关属性 -- 方法链方式
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    // handler 是针对 bossGroup 作配置的
//                    .handler(new LoggingHandler(LogLevel.INFO))
                    // childHandler 是针对 workerGroup 作配置的
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("IdleStateHandler", new IdleStateHandler(0, 0, 30, TimeUnit.SECONDS))
                                    .addLast("IdleTimeOutHandler", IdleTimeOutHandler.INSTANCE)
                                    .addLast("long-decoder", new LongMessageDecoder())
                                    .addLast("long-encoder", new LongMessageEncoder())
                                    .addLast("long-handler", new MyLongMessageHandler());
                        }
                    });
            InetSocketAddress address = new InetSocketAddress(8899);
            ChannelFuture channelFuture = bootstrap.bind(address).sync();
            logger.warn("Server started {}", address);
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
